package com.ysxsoft.wdg.ui.activity.order;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.order.ZyOrderDetailAdapter;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.UserInfoBean;
import com.ysxsoft.wdg.bean.cart.ShopcartBean;
import com.ysxsoft.wdg.bean.response.AplyBackRequestResponse;
import com.ysxsoft.wdg.bean.response.AplyBackResponse;
import com.ysxsoft.wdg.bean.response.AplyBackResponse2;
import com.ysxsoft.wdg.bean.response.MyKanResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.my.ShopRzInputActivity;
import com.ysxsoft.wdg.util.ImageUtils;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.camera.CameraUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.ysxsoft.wdg.widget.alertview.OnItemClickListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

public class AplyBackOrderActivity extends BaseActivity {
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_finish)
    ImageView titleFinish;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_iv_r)
    ImageView titleIvR;
    @BindView(R.id.title_tv_r)
    TextView titleTvR;
    @BindView(R.id.productRecyclerView)
    RecyclerView productRecyclerView;
    @BindView(R.id.totalMoney)
    TextView totalMoney;
    @BindView(R.id.radio1)
    RadioButton radio1;
    @BindView(R.id.radio2)
    RadioButton radio2;
    @BindView(R.id.yuanyin)
    EditText yuanyin;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.description)
    EditText description;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R.id.tv_pay_time)
    TextView tv_pay_time;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.submit)
    Button submit;
    ZyOrderDetailAdapter adapter;
    private String type;
    private String orderid;
    private boolean isManJian;

    public static void start(Context context, String orderId, int type) {
        Intent intent = new Intent(context, AplyBackOrderActivity.class);
        intent.putExtra("orderId", orderId);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    public static void start(Context context, String orderId, int type,boolean isManJian) {
        Intent intent = new Intent(context, AplyBackOrderActivity.class);
        intent.putExtra("orderId", orderId);
        intent.putExtra("type", type);
        intent.putExtra("isManJian", isManJian);//由于申请接口新增type=3   自营和满减区分
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_aplyback_order;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("申请退款");

        //初始化数据
        orderid = getIntent().getStringExtra("orderId");
        isManJian = getIntent().getBooleanExtra("isManJian",false);
        type = getIntent().getIntExtra("type", 0) + "";

        productRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        productRecyclerView.setNestedScrollingEnabled(false);
        productRecyclerView.setFocusable(false);
        adapter = new ZyOrderDetailAdapter(R.layout.include_order_goods);
        productRecyclerView.setAdapter(adapter);
        getDetail();
    }

    @Override
    protected void setListener() {
        //设置监听
    }

    @OnClick({R.id.title_finish, R.id.submit, R.id.image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.submit:
                submit();
                break;
            case R.id.image:
                AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            new RxPermissions(AplyBackOrderActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().takeCamera(AplyBackOrderActivity.this);
                                        }
                                    });
                        } else if (position == 1) {
                            new RxPermissions(AplyBackOrderActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().openAlbum(AplyBackOrderActivity.this);
                                        }
                                    });
                        }
                    }
                }).show();
                break;
        }
    }

    /**
     * 获取详情数据
     */
    private void getDetail() {
        OkHttpUtils.post()
                .url(UrlHost.BACK_ORDER_INFO)
                .addParams("orderid", orderid)//订单id
                .addParams("type", type + "")//1.自营,满减   2实体
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    if("1".equals(type)){//自营/满减商品
                        AplyBackResponse aplyBackResponse = JsonUtils.parseByGson(response, AplyBackResponse.class);
                        if (aplyBackResponse == null) {
                            return;
                        }
                        if (CallbackCode.SUCCESS.equals(aplyBackResponse.getCode())) {
                            AplyBackResponse.DataBean data = aplyBackResponse.getData();
                            if (data != null) {
                                List<AplyBackResponse.DataBean.DetailBean> list = data.getDetail();
                                adapter.setNewData(list);
                                totalMoney.setText("￥" + data.getAccount());
                                money.setText("￥" + data.getAccount());

                                tvOrderTime.setText("订单时间：" + converTimeByUnixTimestemp("yyyy-MM-dd HH:mm:ss",data.getAddtime()));
                                tvOrderNo.setText("订单编号：" + data.getDsn());
                                tv_pay_time.setText("支付时间：" + converTimeByUnixTimestemp("yyyy-MM-dd HH:mm:ss",data.getPaytime()));
                                dsn=data.getDsn();
                            }
                        }
                    }else if("2".equals(type)){//实体退款
                        AplyBackResponse2 aplyBackResponse2 = JsonUtils.parseByGson(response, AplyBackResponse2.class);
                        if (aplyBackResponse2 == null) {
                            return;
                        }
                        if (CallbackCode.SUCCESS.equals(aplyBackResponse2.getCode())) {
                            AplyBackResponse2.DataBean data = aplyBackResponse2.getData();
                            if (data != null) {
                                AplyBackResponse2.DataBean.DetailBean d = data.getDetail();
                                //转换bean对象
                                List<AplyBackResponse.DataBean.DetailBean> ll = new ArrayList<>();
                                AplyBackResponse.DataBean.DetailBean da=new AplyBackResponse.DataBean.DetailBean();
                                da.setPic(d.getPic());
                                da.setProduct_name(d.getName());
                                da.setRule_name(d.getPdesrc());
                                da.setPrice(d.getPrice());
                                da.setNum(d.getNum());
                                ll.add(da);
                                adapter.setNewData(ll);

                                totalMoney.setText("￥" + data.getAccount());
                                money.setText("￥" + data.getAccount());

                                tvOrderTime.setText("订单时间：" + converTimeByUnixTimestemp("yyyy-MM-dd HH:mm:ss",data.getAddtime()));
                                tvOrderNo.setText("订单编号：" + data.getDsn());
                                tv_pay_time.setText("支付时间：" + converTimeByUnixTimestemp("yyyy-MM-dd HH:mm:ss",d.getAddtime()));
                                dsn=data.getDsn();
                            }
                        }
                    }
                } else {
                }
            }
        });
    }

    /**
     * Unix时间戳转换为对应的格式  将时间戳转换为对应的格式 yyyy-MM-dd HH:hh:ss
     * @param format    如 yyyy-MM-dd HH:hh:ss
     * @param unixTimestemp
     * @return
     */
    public static String converTimeByUnixTimestemp(String format, long unixTimestemp) {
        String result = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        result = sdf.format(new Date(unixTimestemp*1000));
        return result;
    }

    private String dsn="";

    /**
     * 申请退款
     */
    private void submit() {
        if ("".equals(yuanyin.getText().toString())) {
            ToastUtils.showToast("请填写退款原因!");
            return;
        }
        if ("".equals(description.getText().toString())) {
            ToastUtils.showToast("请填写退款说明!");
            return;
        }
        if (picid == null) {
            ToastUtils.showToast("请上传凭证!");
            return;
        }
        OkHttpUtils.post()
                .url(UrlHost.BACK_ORDER_APLY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderid)//订单id
                .addParams("status", type + "")//1.自营，满减 2实体
                .addParams("remark", description.getText().toString() + "")//说明
                .addParams("type", radio1.isChecked() ? "1" : "2")//1.仅退款 2.退款退货
                .addParams("reason", yuanyin.getText().toString())//原因
                .addParams("dsn", dsn + "")//订单号
                .addParams("pic", picid)//图片id
                .addParams("style", isManJian?"3":type + "")//1.自营  2实体 3满减
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    AplyBackRequestResponse myKanResponse = JsonUtils.parseByGson(response, AplyBackRequestResponse.class);
                    if (myKanResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(myKanResponse.getCode())) {
                        ToastUtils.showToast(myKanResponse.getMs());
                        finish();
                    }else{
                        ToastUtils.showToast(myKanResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    class ZyOrderDetailAdapter extends BaseQuickAdapter<AplyBackResponse.DataBean.DetailBean, BaseViewHolder> {

        public ZyOrderDetailAdapter(int layoutResId) {
            super(layoutResId);
        }

        public void clear() {
            getData().clear();
            notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, AplyBackResponse.DataBean.DetailBean item) {
            ViewUtils.loadImage(mContext, item.getPic(), (ImageView) helper.getView(R.id.iv_goods));
            helper.setText(R.id.tv_goods_name, item.getProduct_name());
            helper.setText(R.id.tv_rules, item.getRule_name());
            helper.setText(R.id.tv_money, mContext.getString(R.string.price_rmb, item.getPrice()));
            helper.setText(R.id.tv_num, "x" + item.getNum());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
//                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Default).cropPicture(AplyBackOrderActivity.this, path);
                Glide.with(AplyBackOrderActivity.this).load(path).into(image);

                String p=ImageUtils.compress(AplyBackOrderActivity.this,System.currentTimeMillis()+".png",new File(path));
                commitPic(p);//上传图片
            }

            @Override
            public void selectPictureFinish(String path) {
//                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Default).cropPicture(AplyBackOrderActivity.this, path);
                Glide.with(AplyBackOrderActivity.this).load(path).into(image);
                String p=ImageUtils.compress(AplyBackOrderActivity.this,System.currentTimeMillis()+".png",new File(path));
                commitPic(p);//上传图片
            }

            @Override
            public void cropPictureFinish(String path) {
            }
        });
    }

    private String picid;

    private void commitPic(String path) {
        mApiHelper.commitPic(path, new Observer<BaseBean<UserInfoBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<UserInfoBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    picid = baseBean.getData().getId();
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }
}
